package cn.kgc.musicserver.service.impl;

import cn.kgc.musicserver.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileStorageServiceImpl implements FileStorageService {
    //歌手文件夹
//    @Value("${file.upload-dir}")
//    private String uploadDir;

    // 上传目录
    @Value("${file.path}")
    private String path;

    @Override
    public String storeFile(MultipartFile file) throws IOException {
        // 创建上传目录
        Path uploadPath = getUploadPath();
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

        // 保存文件
        Path targetLocation = uploadPath.resolve(fileName);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    }

    @Override
    public Path getUploadPath() {
//        return Paths.get(uploadDir).toAbsolutePath().normalize();
        return Paths.get(path + File.separator + "images" + File.separator + "singerPic").toAbsolutePath().normalize();
    }

    /**
     * 存储文件到指定目录
     *
     * @author 王玉林
     * @param file 文件
     * @param path 目录
     * @return 文件名
     * @throws IOException
     */
    @Override
    public String storeFile(MultipartFile file, String path) throws IOException {
        // 创建上传目录
        Path uploadPath = getUploadPath(path);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

        // 保存文件
        Path targetLocation = uploadPath.resolve(fileName);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    }

    /**
     * 获取上传目录
     *
     * @author 王玉林
     * @param subPath 子目录
     * @return 上传目录
     */
    @Override
    public Path getUploadPath(String subPath) {
        return Paths.get(path + File.separator + subPath).toAbsolutePath().normalize();
    }
}
